package com.zoe.app.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.zoe.app.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.StringJoiner;

/**
 * @author Zoe.Zhang
 * @date 2021/10/06
 * @description
 */
@RestController
public class SingleFileUploadController {
    @PostMapping("/single")
    public String singleFile(MultipartFile file, HttpServletRequest request) throws IOException {
        String realPath = request.getServletContext().getRealPath("/");
        DateTime date = DateUtil.date();
        String formatPath = DateUtil.format(date, "/yyyy/MM/dd/");
        String path = realPath + formatPath;
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = IdUtil.fastSimpleUUID() + StrUtil.subSuf(oldName, StrUtil.lastIndexOfIgnoreCase(oldName, "."));
        file.transferTo(new File(folder + newName));
        String reqUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + formatPath + newName;
        return reqUrl;
    }

    @PostMapping("/multipartFile")
    public String multipartFile(List<MultipartFile> file, User user) throws IOException {
        StringJoiner stringJoiner = new StringJoiner(",");
        System.out.println(user);
        for (MultipartFile multipartFile : file) {
            System.out.println(multipartFile.getOriginalFilename());
            stringJoiner.add(multipartFile.getOriginalFilename());
        }
        return stringJoiner.toString();
    }
}
